package com.dayuanit.controller;

import java.io.File;
import java.io.IOException;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.dayuanit.content.Content;
import com.dayuanit.domain.User;
import com.dayuanit.dto.AjaxResultDTO;
import com.dayuanit.exception.MallException;
import com.dayuanit.service.UserService;
import com.dayuanit.utils.MailUtil;
import com.dayuanit.vo.UserVO;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "/modifyPassword")
	@ResponseBody
	public AjaxResultDTO modifyPassword(UserVO vo, HttpServletRequest req) {
		User user = userService.getUser(vo.getUserName());
		if (null != vo.getPassword() && !"".equals(vo.getPassword()) && vo.getPassword().equals(vo.getPasswordRepeat())) {
			user.setPassword(vo.getPassword());
			userService.modifyPassword(user);
		} else {
			return AjaxResultDTO.failed("密码输入不一致，请重新输入");
		}
		req.getSession().setAttribute("message", "密码修改成功，请前去登录。");
		return AjaxResultDTO.success("密码修改成功，请前去登录。");
	}

	@RequestMapping("/toForget")
	public String toForget() {
		return "forward:/WEB-INF/jsp/forget.jsp";
	}

	@RequestMapping("/toModifyPassword")
	public String toModifyPassword(UserVO vo, HttpServletRequest req) {
		User user = userService.getUser(vo.getUserName());
		if (null != user && vo.getMail().equals(user.getMail())) {
			req.getSession().setAttribute("mark", vo.getUserName());
			return "forward:/WEB-INF/jsp/modifyPassword.jsp";
		} else {
			req.setAttribute("message", "用户名或邮箱有误！");
			return "forward:/WEB-INF/jsp/forget.jsp";
		}
	}

	@RequestMapping("/forget")
	@ResponseBody
	public AjaxResultDTO forget(UserVO vo, HttpServletRequest req) throws AddressException, MessagingException {
		try {
			User user = userService.getUser(vo.getUserName());
			
			if (null == user) {
				throw new RuntimeException("用户名有误");
			}
			
			if (null == vo.getMail() || "".equals(vo.getMail())) {
				throw new RuntimeException("邮箱不能为空");
			}
			
			if (!vo.getMail().equals(user.getMail())) {
				throw new RuntimeException("邮箱有误");
			}
			
			if (null == vo.getVerificationCode() || "".equals(vo.getVerificationCode())) {
				throw new RuntimeException("验证码不能为空");
			}
			
			if (!req.getSession().getAttribute(CodeController.CODE_FLAG).equals(vo.getVerificationCode())) {
				throw new RuntimeException("验证码输入错误");
			}
			if (null != user && !"".equals(user) && vo.getMail().equals(user.getMail())) {
				MailUtil.forget(vo.getMail(), vo.getUserName());
				req.getSession().setAttribute("message", "邮件发送成功，请去邮箱重置密码。");
			} else {
				req.getSession().setAttribute("message", "用户名或邮箱有误！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResultDTO.failed(e.getMessage());
		}
		return AjaxResultDTO.success("邮件发送成功，请去邮箱重置密码");
	}

	@RequestMapping(value = "/activation", method = RequestMethod.GET)
	public String activation(HttpServletRequest req) {
		String code = req.getParameter("code");
		User user = userService.getUserByCode(code);
		if (null != user) {
			user.setState(1);
			user.setCode(null);
			userService.modifyState(user);
			req.setAttribute("message", "您已经激活成功，请去登录。");
			return "forward:/WEB-INF/jsp/success.jsp";
		} else {
			req.setAttribute("message", "您的激活码有误，请重新激活。");
		}
		return "forward:/WEB-INF/jsp/success.jsp";
	}

	@RequestMapping(value = "/upload")
	public String upload(@RequestParam("file") MultipartFile mf, HttpServletRequest req) throws Exception {
		User user = (User) req.getSession().getAttribute(Content.LOGIN_FLAG);
		File file = new File("D:/workspace/mall/src/main/webapp/images/" + user.getId());
		if (!mf.isEmpty()) {
			FileUtils.copyInputStreamToFile(mf.getInputStream(), file);
		}
		return "home.page";
	}

	@RequestMapping("/toMyZone")
	public String toMyZone(HttpServletRequest req) throws ServletException, IOException {
		HttpSession hs = req.getSession();
		if (null == hs.getAttribute(Content.LOGIN_FLAG)) {
			return "login.page";
		}
		return "forward:/WEB-INF/jsp/upload.jsp";
	}
	
	@RequestMapping("/toHome")
	public String toHome() {
		return "home.page";
	}
	
	@RequestMapping("/toLogin")
	public String toLogin() {
		return "login.page";
	}
	
	@RequestMapping("/toRegister")
	public String toRegister() {
		return "regist.page";
	}
	
	@RequestMapping("/success")
	public String success() {
		return "forward:/WEB-INF/jsp/success.jsp";
	}

	@RequestMapping("/regist")
	@ResponseBody
	public AjaxResultDTO regist(UserVO vo, HttpSession session) {
		
		try {
			String verificationCode = (String) session.getAttribute(CodeController.CODE_FLAG);
			if (!verificationCode.equalsIgnoreCase(vo.getVerificationCode())) {
				return AjaxResultDTO.failed("验证码有误");
			}
			userService.addUser(vo);
		} catch (MallException e) {
			return AjaxResultDTO.failed(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResultDTO.failed("注册失败");
		} finally {
			session.removeAttribute(CodeController.CODE_FLAG);
		}
		session.setAttribute("message", "您已经注册成功，请去邮箱激活。");
		return AjaxResultDTO.success("注册成功");
	}

	@RequestMapping("/login")
	@ResponseBody
	public AjaxResultDTO login(UserVO vo, HttpSession session) {
		try {
			User user = userService.login(vo);
			session.setAttribute(Content.LOGIN_FLAG, user);
		} catch (MallException e) {
			return AjaxResultDTO.failed(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			session.setAttribute("message", e.getMessage());
			return AjaxResultDTO.failed(e.getMessage());
		}
	
		return AjaxResultDTO.success("登录成功");
	}

	@RequestMapping("/loginOut")
	public String loginOut(HttpServletRequest req) {
		HttpSession session = req.getSession(false);
		if (null == session) {
			return "login.page";
		}
		session.removeAttribute(Content.LOGIN_FLAG);
		return "login.page";
	}
}